package com.guan.springmvc.demo;

import ch.qos.logback.core.util.StringUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @PostMapping("/login")
    public Boolean login(String userName, String password, HttpSession session) {
        // 1. 参数校验
        // 2. 验证密码是否正确
        // 3. 进行返回

//        // 养成习惯将常量写在 .equals 前边
//        if (userName == null || "".equals(userName)
//                || password == null || "".equals(password)) {
//            return false;
//        }

        // 使用 spring 提供的工具类
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return false;
        }

        // 验证密码是否正确，理论来说应该去访问数据库
        // 暂且硬编码写死
        if ("admin".equals(userName) && "admin".equals(password)) {
            session.setAttribute("loginUserName", userName);
            return true;
        }
        return false;
    }

    @GetMapping("/getLoginUser")
    public String getLoginUser(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return "";
        }
        return (String) session.getAttribute("loginUserName");
    }
}
